﻿using mds.BaseFrameModel;
using mds.NoSqlDatabase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace mds.DFSService
{
    public class DistributedFileProvider : IDistributedFileProvider
    {
        public DistributedFileProvider()
        {

        }


        public BaseFrameModel.OperationResult<DistributedFile> Save(string spaceKey, Guid fileId, string fileName, string fileSuffix, byte[] filedata, string fileType)
        {
            var result = new DistributedFile()
            {
                FileData = filedata,
                FileExtension = fileType,
                FileName = fileName,
                FileSize = filedata.Length,
                FileSuffix = fileSuffix,
                Id = fileId,
                KeySpace = spaceKey
            };
            result.Id = CassandraProvider.Instance.AddFile(new CassandraFile()
            {
                KeySpace = spaceKey,
                FileSuffix = fileSuffix,
                FileSize = filedata.Length,
                FileName = fileName,
                FileExtension = fileSuffix,
                FileData = filedata,
                Id = fileId
            }, DFSConfigService.Instance.GetConnection());
            return new OperationResult<DistributedFile>(result, (result.Id != Guid.Empty) ? true : false);
        }

        public BaseFrameModel.OperationResult<bool> Delete(string spaceKey, Guid fileId)
        {
            return new OperationResult<bool>(CassandraProvider.Instance.DropFile(fileId, spaceKey,DFSConfigService.Instance.GetConnection()));
        }

        public BaseFrameModel.OperationResult<DistributedFile> GetFile(string spaceKey, Guid fileId)
        {
            var fileData = CassandraProvider.Instance.GetFile(fileId, spaceKey, DFSConfigService.Instance.GetConnection());
            var result = new OperationResult<DistributedFile>((fileData != null) ? true : false);
            if (result.ActionResult)
            {
                result.Data = new DistributedFile()
                {
                    FileData = fileData.FileData,
                    Id = fileData.Id,
                    FileExtension = fileData.FileExtension,
                    FileName = fileData.FileName,
                    FileSize = fileData.FileData.Length,
                    FileSuffix = fileData.FileSuffix,
                    KeySpace = fileData.KeySpace
                };
            }
            return result;
        }
    }
}
